<template>
  <scroll-view scroll-y="ture" style="height: 100vh">
    <view
      class="panda-container"
      :style="{
        backgroundImage: `url(${oss2('others/panda2023/pic_yindao.png')})`,
      }"
    >
      <view
        class="back"
        @click="backIndex"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/but_back2.png')})`,
        }"
      ></view>
      <view
        class="myPrize"
        @click.stop="toMyPrize"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/but_mygift.png')})`,
        }"
      ></view>

      <!-- <view
        class="scanCode"
        @click="scanCode"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/but_saoma.png')})`,
        }"
      ></view> -->
      <view
        class="toBuy"
        @click="toBuy"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/but_buy.png')})`,
        }"
      ></view>

      <!-- <view
        class="toInput"
        @click="toInput"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/sdhx_pic.png')})`,
        }"
      ></view> -->
    </view>

    <!-- 弹窗1 -->
    <view class="mode" v-if="showDialog1">
      <view
        class="Dialog_body w-305.5px h-282.5px top-209px left-35px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/tk_bg.png')})`,
        }"
        ><view
          class="Dialog_back w-119px h-44.5px bottom-47px left-93px"
          @click.stop="openDialog1"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
        <view class="Dialog_rule bottom-18.5px"
          >查看<span class="link" @click.stop="openRule">活动规则</span>
        </view>
      </view>
    </view>

    <!-- 弹窗2 -->
    <view class="mode" v-if="showDialog2">
      <view
        class="Dialog_body w-310px h-295px top-209px left-35px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/tcpic_3.png')})`,
        }"
        ><view
          class="Dialog_back w-119px h-44.5px bottom-68px left-93px"
          @click.stop="openDialog2"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
        <view class="Dialog_rule bottom-36.5px"
          >查看<span class="link" @click.stop="openRule">活动规则</span>
        </view>
      </view>
    </view>

    <!-- 弹窗3 -->
    <view class="mode" v-if="showDialog3">
      <view
        class="Dialog_body w-310px h-295px top-209px left-35px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/tcpic_4.png')})`,
        }"
        ><view
          class="Dialog_back w-119px h-44.5px bottom-68px left-93px"
          @click.stop="openDialog3"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
        <view class="Dialog_rule bottom-36.5px"
          >查看<span class="link" @click.stop="openRule">活动规则</span>
        </view>
      </view>
    </view>

    <!-- 活动结束弹窗 -->
    <view class="mode" v-if="showEndDialog">
      <view
        class="Dialog_body w-320px h-300px top-202px left-27px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/panda_end.png')})`,
        }"
      >
        <view
          class="Dialog_back w-140px h-48px bottom-51px left-90px"
          @click.stop="backIndex"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
      </view>
    </view>

    <oreo-action-sheet
      :show="kefuShow"
      @cancel="kefuShow = false"
      cancel-text="取消"
    >
      <button class="phoneStyle" @click="PhoneCall">400-0880-325</button>
      <button open-type="contact" class="kefu_btn">在线客服</button>
    </oreo-action-sheet>

    <!-- 活动规则弹窗 -->
    <rule-popup
      v-if="showRule"
      @closekf="kefuShow = false"
      @openkf="kefuShow = true"
      @close="showRule = false"
    />
  </scroll-view>


</template>

<script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { oss2, generateSign2, message } from "@/utils/utils";
import RulePopup from "./components/rule-popup.vue";
import { userLogin } from "@/services/utils";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const code = ref("");

const showDialog1 = ref(false);
const showDialog2 = ref(false);
const showDialog3 = ref(false);
const showRule = ref(false);
const kefuShow = ref(false);
const firstPage = ref(false);

const showEndDialog = ref(false);

onLoad(async (query) => {
  firstPage.value = true;

  const pages = getCurrentPages();
  console.log(pages);
  const beforePage = pages[pages.length - 2]?.route ?? "";

  if (beforePage !== "campaign/pages/panda2023/index") {
    const codeValue = decodeURIComponent(
      query.q ? query.q : uni.getLaunchOptionsSync().query.q
    );
    console.log(codeValue);
    code.value = codeValue.split("/")[codeValue.split("/").length - 1];

    if (!uni.getStorageSync("OPENID")) {
      getApp()
        .getUserLoginInfo()
        .then((info) => {
          return getApp()
            .getUserInfo()
            .then((user) => {
              linkTo(
                `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
                  "TOKEN"
                )}&code=${code.value}&openid=${uni.getStorageSync(
                  "OPENID"
                )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                  user.memberScore.memberId
                }&agree=${uni.getStorageSync("PANDAAGREE")}`
              );
            });
          const body = {
            userValue: info.openId,
            qrCode: code.value,
            source: "oreo",
            timestamp: Date.parse(new Date()),
          };
          uni.request({
            url: `${process.env.PANDA_URL2}/zex-qr/api/qr/validation`,
            method: "get",
            data: {
              ...body,
              ...{ sign: generateSign2(body) },
            },

            success: async (requestRes) => {
              console.log(requestRes);
              if (requestRes.data.code === 200) {
                getApp()
                  .getUserInfo()
                  .then((user) => {
                    linkTo(
                      `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
                        "TOKEN"
                      )}&code=${code.value}&openid=${uni.getStorageSync(
                        "OPENID"
                      )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                        user.memberScore.memberId
                      }&agree=${uni.getStorageSync("PANDAAGREE")}`
                    );
                    code.value = "";
                  });
              } else if ([4000].includes(requestRes.data.code)) {
                code.value = "";
                showDialog1.value = true;
              } else if ([4001].includes(requestRes.data.code)) {
                code.value = "";
                showDialog2.value = true;
              } else if ([4002].includes(requestRes.data.code)) {
                code.value = "";
                showDialog3.value = true;
              } else {
                code.value = "";
                uni.showToast({
                  title: requestRes.data.message,
                  icon: "none",
                  duration: 2000,
                });
              }
            },
            fail(requestErr) {
              code.value = "";
              uni.showToast({
                title: requestErr.data.message,
                icon: "none",
                duration: 2000,
              });
            },
          });
        });
    } else {
      return getApp()
        .getUserInfo()
        .then((user) => {
          linkTo(
            `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
              "TOKEN"
            )}&code=${code.value}&openid=${uni.getStorageSync(
              "OPENID"
            )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
              user.memberScore.memberId
            }&agree=${uni.getStorageSync("PANDAAGREE")}`
          );
          code.value = "";
        });

      const body = {
        userValue: uni.getStorageSync("OPENID"),
        qrCode: code.value,
        source: "oreo",
        timestamp: Date.parse(new Date()),
      };
      uni.request({
        url: `${process.env.PANDA_URL2}/zex-qr/api/qr/validation`,
        method: "get",
        data: {
          ...body,
          ...{ sign: generateSign2(body) },
        },

        success: async (requestRes) => {
          console.log(requestRes);
          if (requestRes.data.code === 200) {
            getApp()
              .getUserInfo()
              .then((user) => {
                linkTo(
                  `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
                    "TOKEN"
                  )}&code=${code.value}&openid=${uni.getStorageSync(
                    "OPENID"
                  )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                    user.memberScore.memberId
                  }&agree=${uni.getStorageSync("PANDAAGREE")}`
                );
                code.value = "";
              });
          } else if ([4000].includes(requestRes.data.code)) {
            code.value = "";
            showDialog1.value = true;
          } else if ([4001].includes(requestRes.data.code)) {
            code.value = "";
            showDialog2.value = true;
          } else if ([4002].includes(requestRes.data.code)) {
            code.value = "";
            showDialog3.value = true;
          } else {
            code.value = "";
            uni.showToast({
              title: requestRes.data.message,
              icon: "none",
              duration: 2000,
            });
          }
        },
        fail(requestErr) {
          code.value = "";
          uni.showToast({
            title: requestErr.data.message,
            icon: "none",
            duration: 2000,
          });
        },
      });
    }
  }
});

onShow(() => {
  // 用户进入时间
  enterTime = new Date();
  getApp().accessLogAdd();
  if (new Date().getTime() > 1692979199000) {
    showEndDialog.value = true;
  }

  // if (code.value !== "" && firstPage.value !== true) {
  //   const codeValue = code.value;
  //   code.value = "";
  //   linkTo(
  //     `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
  //       "TOKEN"
  //     )}&code=${codeValue}&openid=${uni.getStorageSync(
  //       "OPENID"
  //     )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
  //       getApp().globalData.user.memberScore.memberId
  //     }`
  //   );
  // }
  // firstPage.value = false;
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;

  getApp().emdlz2(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "view",
    "campaign_landpage",
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "view",
    "campaign_landpage",
    stayTime
  );
});

const scanCode = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "go_scan",
    ""
  );
  uni.scanCode({
    scanType: ["qrCode"],
    success: async (res) => {
      console.log(res);
      code.value = res.result.split("/")[res.result.split("/").length - 1];
      console.log(res.result.split("/"));

      const body = {
        userValue: uni.getStorageSync("OPENID"),
        qrCode: code.value,
        source: "oreo",
        timestamp: Date.parse(new Date()),
      };
      uni.request({
        url: `${process.env.PANDA_URL2}/zex-qr/api/qr/validation`,
        method: "get",
        data: {
          ...body,
          ...{ sign: generateSign2(body) },
        },

        success: async (requestRes) => {
          console.log(requestRes);
          if (requestRes.data.code === 200) {
            // 是否登录注册
            if (!uni.getStorageSync("TOKEN")) {
              // 静默拿取微信用户的 openId 与 unionId 信息
              uni.login({
                provider: "weixin",
                success: async (res) => {
                  console.log(res);
                  const loginParam = {
                    type: 1,
                  };
                  loginParam.code = res.code;
                  const { data } = await userLogin(loginParam);
                  uni.setStorageSync("TOKEN", data?.accessToken);
                  uni.setStorageSync("OPENID", data?.openId);
                  uni.setStorageSync("UNIONID", data?.unionId);
                  getApp().emdlz("set", "user", "openid", data?.openId);
                  getApp().emdlz("set", "user", "unionId", data?.unionId);

                  linkTo(
                    `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
                      "TOKEN"
                    )}&code=${code.value}&openid=${uni.getStorageSync(
                      "OPENID"
                    )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                      getApp().globalData.user.memberScore.memberId
                    }&agree=${uni.getStorageSync("PANDAAGREE")}`
                  );
                  code.value = "";
                },
              });
            } else {
              linkTo(
                `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
                  "TOKEN"
                )}&code=${code.value}&openid=${uni.getStorageSync(
                  "OPENID"
                )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                  getApp().globalData.user.memberScore.memberId
                }&agree=${uni.getStorageSync("PANDAAGREE")}`
              );
              code.value = "";
            }
          } else if ([4000].includes(requestRes.data.code)) {
            code.value = "";
            showDialog1.value = true;
          } else if ([4001].includes(requestRes.data.code)) {
            code.value = "";
            showDialog2.value = true;
          } else if ([4002].includes(requestRes.data.code)) {
            code.value = "";
            showDialog3.value = true;
          } else {
            code.value = "";
            uni.showToast({
              title: requestRes.data.message,
              icon: "none",
              duration: 2000,
            });
          }
        },
        fail(requestErr) {
          code.value = "";
          uni.showToast({
            title: requestErr.data.message,
            icon: "none",
            duration: 2000,
          });
        },
      });
    },
    fail(err) {
      console.log(err);
    },
  });
};

const linkTo = (url) => uni.navigateTo({ url });

const linkToWebView = (url) => {
  linkTo(
    `/pages/webView/webview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${url}&agree=${uni.getStorageSync(
      "PANDAAGREE"
    )}&shareTitel=泡出童心 玩在一起&shareImg=${oss2(
      "others/panda2023/sharepic2.png"
    )}&path=${"/campaign/pages/panda2023/index?from=pubid:shareback;aid:sharecard"}`
  );
};

const toMyPrize = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "my_prize",
    ""
  );
  linkToWebView(`${process.env.PANDA_URL2}/a/record.html`);
};

const openDialog1 = () => {
  showDialog1.value = false;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "qr_code_invalidation_return",
    ""
  );
};

const openDialog2 = () => {
  showDialog2.value = false;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "qr_code_invalidation_return",
    ""
  );
};
const openDialog3 = () => {
  showDialog3.value = false;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "qr_code_invalidation_return",
    ""
  );
};

const openRule = () => {
  showRule.value = true;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "check_activity_rule",
    ""
  );
};

const toBuy = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "go_buy",
    ""
  );
  uni.switchTab({
    url: "/pages/mall/mall",
  });
};

const toInput = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "hm_cancel_after_verification",
    ""
  );
  linkTo("/campaign/pages/panda2023/scanCodeInput");
};

const PhoneCall = () => {
  uni.makePhoneCall({
    phoneNumber: "400-0880-325",
  });
};

const backIndex = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_scan_page",
    "click",
    "return",
    ""
  );
  const pages = getCurrentPages();
  const beforePage = pages[pages.length - 2]?.route ?? "";
  if (beforePage !== "campaign/pages/panda2023/index") {
    uni.redirectTo({
      url: "/campaign/pages/panda2023/index",
    });
  } else {
    uni.navigateBack({
      delta: 1,
    });
  }
};

onShareAppMessage((e) => {
  // const pages = getCurrentPages();
  // const currentPage = pages[pages.length - 1];
  // console.log(pages);
  // const pageUrl = currentPage.$page.fullPath;

  const shareObj = {
    title: "泡出童心 玩在一起", // 默认是小程序的名称(可以写slogan等)
    path: "/campaign/pages/panda2023/index?from=pubid:shareback;aid:sharecard", // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("others/panda2023/sharepic2.png"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});
</script>

<style>
page {
  background-color: #0a2080 !important;
}
</style>
<style lang="less" scoped>
.panda-container {
  width: 100%;
  background-color: #1335b3;
  height: 724px;
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 375px 100%;
  position: relative;

  .back {
    position: absolute;
    top: 21px;
    left: 0;
    width: 61px;
    height: 32px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 61px 100%;
  }
  .myPrize {
    position: absolute;
    top: 21px;
    right: 0;
    width: 96px;
    height: 32px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 96px 100%;
  }
  .scanCode {
    position: absolute;
    width: 192px;
    height: 50px;
    top: 528.5px;
    left: 91.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 192px 100%;
  }
  .toBuy {
    position: absolute;
    width: 192px;
    height: 45px;
    top: 588px;
    left: 91.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 192px 100%;
  }

  .toInput {
    position: absolute;
    width: 192px;
    height: 20px;
    top: 639px;
    left: 91.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 192px 100%;
  }
}

.mode {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 90;
  background-color: rgba(10, 28, 108, 0.8);
  .Dialog_body {
    position: absolute;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
    .Dialog_back {
      position: absolute;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 100% 100%;
    }
    .Dialog_rule {
      width: 100%;
      text-align: center;
      font-size: 12.5px;
      position: absolute;
      color: #0f2989;
      .link {
        color: #30a8fb;
        text-decoration: underline;
        margin-left: 5px;
      }
    }
  }
}

.phoneStyle {
  font-size: 16px;
  color: #007aff;
}
.kefu_btn {
  font-size: 16px;
  margin: 0 !important;
  border-radius: 0 !important;
  background: none !important;
}
</style>
